﻿using Helper;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Principal;
using System.Text;
using System.Web;
using System.Web.SessionState;

namespace Langchur.ApiFilter
{
    /// <summary>
    /// ApiRoute 的摘要说明
    /// </summary>
    public class ApiRoute : IHttpHandler, IRequiresSessionState
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            context.Response.Write(PostApi(context));
        }

        private class UserLogin
        {
            private UserLoginTable _data = new UserLoginTable();
            public UserLoginTable data
            {
                set { _data = value; }
                get { return _data; }
            }
        }

        private class UserLoginTable
        {
            private List<Account> _table = new List<Account>();
            public List<Account> table
            {
                set { _table = value; }
                get { return _table; }
            }
        }


        private String PostApi(HttpContext context)
        {
            string url = "";//地址  
            string getUrl = "";
            string postString = "";
            Boolean IsAdminLogin = false; // 管理登录
            Boolean IsMemberLogin = false;

            String SaveAddress = System.Configuration.ConfigurationManager.AppSettings["SaveAddress"];
            String[] SaveAddressGroup = SaveAddress.Split(';');

            ApiHandle handle = new ApiHandle();
            bool isFailUrl = true;
            for (int i = 0; i < SaveAddressGroup.Length; i++)
            {
                if (SaveAddressGroup[i] == "")
                {
                    continue;
                }

                if (context.Request.UrlReferrer.AbsoluteUri.StartsWith(SaveAddressGroup[i]))
                {
                    isFailUrl = false;
                    break;
                }
            }

            if (isFailUrl)
            {
                throw new Exception("非法地址操作!");
            }

            System.IO.Stream sream = context.Request.InputStream;
            StreamReader sr = new StreamReader(sream);
            string strXML = sr.ReadToEnd().Replace("&amp;", "").Replace("&lt;", "").Replace("#", "%23")
                .Replace("&gt;", "").Replace("&nbsp;", "").Replace("&quot;", "").Replace(Environment.NewLine, "");

            strXML = context.Server.HtmlDecode(strXML);

            String Method = "POST";


            var useOld = false;
            Uri virUrl = null;
            try
            {
                virUrl = new Uri("http://test.html?filxxs=123&" + strXML);
            }
            catch
            {
                useOld = true;
            }
            if (!useOld)
            {
                var collection = HttpUtility.ParseQueryString(virUrl.Query);

                foreach (String key in collection.AllKeys)
                {
                    if (String.IsNullOrEmpty(key))
                    {
                        continue;
                    }
                    if (key.ToLower() == "apiurl")
                    {
                        if (!collection[key].StartsWith("http"))
                        {
                            url = ConfigManager.GetAppSettings("ApiUrl") + collection[key];
                        }
                        else
                        {
                            url = collection[key];
                        }
                        //url = collection[key];
                    }
                    else if (key.ToLower() == "method")
                    {
                        Method = collection[key];
                        url = collection["apiurl"];
                    }
                    else
                    {
                        if (key == "Name")
                        {
                            handle.Action = collection[key];
                        }
                        handle.Parms.Add(key, collection[key]);
                        if (key == "Name" && collection[key] == "adminLogin")
                        {
                            IsAdminLogin = true;
                        }
                        if (key == "Name" && collection[key] == "LoginByExamNo")
                        {
                            IsMemberLogin = true;
                        }
                        getUrl += key + "=" + collection[key] + "&";
                        if (Boolean.Parse(context.Request.QueryString["list"]))
                        {
                            if ((collection[key].StartsWith("[") && collection[key].EndsWith("]"))
                                || (collection[key].StartsWith("{") && collection[key].EndsWith("}")))
                            {
                                postString += "\"" + key + "\":" + collection[key].Replace("%23", "#") + ",";
                            }
                            else
                            {
                                postString += "\"" + key + "\":\"" + collection[key].Replace("%23", "#") + "\",";
                            }
                        }
                        else
                        {

                            postString += "\"" + key + "\":\"" + collection[key].Replace("%23", "#") + "\",";
                        }
                    }
                }
            }
            else
            {
                foreach (String s in strXML.Split('&'))
                {
                    string[] kv = s.Split('=');
                    if (kv[0].ToLower() == "apiurl")
                    {
                        //设置需要调用的API
                        //http://localhost:37019/apis/Files/GetDataByDay
                        if (kv[1].IndexOf("http://") != -1)
                        {
                            url = kv[1];
                        }
                        else
                        {
                            url = ConfigManager.GetAppSettings("ApiUrl") + kv[1];
                        }
                        continue;
                    }
                    if (kv[0].ToLower() == "method")
                    {
                        Method = kv[1];
                    }

                    if (kv[1] == "adminLogin")
                    {
                        IsAdminLogin = true;
                    }
                    if (kv[1] == "X5_MemberLogin")
                    {
                        IsMemberLogin = true;
                    }
                    if (kv[0] == "Name")
                    {
                        handle.Action = kv[1];
                    }
                    handle.Parms.Add(kv[0], kv[1]);
                    if (kv.Length > 2)
                    {
                        String key = kv[0];
                        String k = "";

                        for (Int32 i = 1; i < kv.Length; i++)
                        {
                            k += kv[i] + "=";
                        }
                        if (k.Length > 0)
                        {
                            k = k.Substring(0, k.Length - 1);
                        }

                        if (Boolean.Parse(context.Request.QueryString["list"]))
                        {
                            if (kv[1].StartsWith("["))
                            {
                                postString += "\"" + key + "\":" + k + ",";
                            }
                            else
                            {
                                postString += "\"" + key + "\":\"" + k + "\",";
                            }
                        }
                        else
                        {

                            postString += "\"" + key + "\":\"" + k + "\",";
                        }
                    }
                    else
                    {
                        if (Boolean.Parse(context.Request.QueryString["list"]))
                        {
                            if (kv[1].StartsWith("[") || kv[1].StartsWith("{"))
                            {
                                postString += "\"" + kv[0] + "\":" + kv[1] + ",";
                            }
                            else
                            {
                                postString += "\"" + kv[0] + "\":\"" + kv[1] + "\",";
                            }
                        }
                        else
                        {
                            if (kv[1].StartsWith("{") && kv[1].EndsWith("}"))
                            {
                                postString += "\"" + kv[0] + "\":" + kv[1] + ",";
                            }
                            else
                            {
                                postString += "\"" + kv[0] + "\":\"" + kv[1] + "\",";
                            }
                        }
                    }
                }
            }

            String Setting = "\"AuthCode\":\"" + System.Configuration.ConfigurationManager.AppSettings["AuthCode"]
                + "\",\"OpUid\":" + context.Request.QueryString["OU"];

            postString = "{" + postString + Setting + "}";

            if (url == "")
            {
                throw new Exception("需要apiurl参数.");
            }

            postString = context.Server.UrlEncode(postString);

            //postString = "{\"AuthorId\":\"ff\",\"Name\":\"CaptialInfo\",\"ID\":\"1\",\"Parameters\":[{}]}";

            byte[] postData = Encoding.UTF8.GetBytes(HttpContext.Current.Server.UrlDecode(postString));//编码，尤其是汉字，事先要看下抓取网页的编码方式  

            WebClient webClient = new WebClient();
            webClient.Headers.Add("Content-Type", "application/json;charset=UTF-8");//采取POST方式必须加的header，如果改为GET方式的话就去掉这句话即可   
            byte[] responseData = null;
            try
            {
                if (Method.ToLower() == "get")
                {
                    if (getUrl.Length > 0)
                    {
                        getUrl = getUrl.Substring(0, getUrl.Length - 1);
                    }
                    if (url.IndexOf('?') != -1)
                    {
                        getUrl = "&" + getUrl;
                    }
                    else
                    {
                        getUrl = "?" + getUrl;
                    }
                    String trUrl = ConfigManager.GetAppSettings("ApiUrl") + url + getUrl;
                    responseData = webClient.DownloadData(trUrl);
                }
                else
                {
                    responseData = webClient.UploadData(url, "POST",
                        postData);//得到返回字符流   
                }
            }
            catch (Exception e)
            {
                throw new Exception("重新登录" + "[{\"ErrorApi\":\"" + url + "\",\"ErrorApiParas\":\"" + postString + "\",\"msg\":\"" + e.Message + "\"}]");
            }
            string srcString = Encoding.UTF8.GetString(responseData);//解码   
            handle.Start();
            if (IsAdminLogin)
            {
            }
            if (IsMemberLogin)
            {
                UserLogin user = new UserLogin();
                user = Newtonsoft.Json.JsonConvert.DeserializeObject<UserLogin>(srcString);
                if (user.data.table.Count > 0)
                {
                    context.Session["User"] = user.data.table[0];
                }
            }

            return srcString;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}